package alex.cicy.monitor;

import alex.cicy.Env;
import alex.cicy.ServerUtils;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.codahale.metrics.graphite.Graphite;
import com.codahale.metrics.graphite.GraphiteReporter;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.codahale.metrics.health.jvm.ThreadDeadlockHealthCheck;
import com.codahale.metrics.jvm.*;
import org.apache.commons.lang3.StringUtils;

import java.lang.management.ManagementFactory;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

import static com.codahale.metrics.MetricRegistry.name;
public abstract class MetricsHelper {
    public static final MetricRegistry metrics = new MetricRegistry();
    private static HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();
    private static String ip = Env.isDev() ? ServerUtils.getHostAddress(Env.innerIP) :
            ServerUtils.getHostAddress(Env.outerIP);


    static {
        metrics.register("jvm.gc", new GarbageCollectorMetricSet());
        metrics.register("jvm.memory", new MemoryUsageGaugeSet());
        metrics.register("jvm.thread-states", new ThreadStatesGaugeSet());
        metrics.register("jvm.fd.usage", new FileDescriptorRatioGauge());
        metrics.register("jvm.buffers", new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
        healthCheckRegistry.register("deadlocks", new ThreadDeadlockHealthCheck());

     /*   Slf4jReporter reporter = Slf4jReporter.forRegistry(metrics)
                .outputTo(LoggerFactory.getLogger("logger-metrics"))
                .convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .build();
        reporter.start(5, TimeUnit.MINUTES);*/
    }

    public static MetricRegistry getMetric() {
        return metrics;
    }

    public static Timer timer(String project, String module, String... names) {
        return metrics.timer(name(project, module, ip.replace('.', '_'), StringUtils.join(names, ".")));
    }

    public static String ip() {
        return ip;
    }
    public static void registerGraphite(String projectName) {
        if(Env.isDev()) return;
        Graphite graphite = new Graphite(new InetSocketAddress("183.61.119.92", 2003));
        GraphiteReporter reporter = GraphiteReporter.forRegistry(metrics)
                .prefixedWith((Env.isStage()?"stage_":"")+projectName)
                .convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .filter(MetricFilter.ALL)
                .build(graphite);
        reporter.start(5, TimeUnit.MINUTES);
    }
}
